package com.ms.p2p.template.method;


import freemarker.ext.beans.StringModel;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by xing_ on 2017/5/24.
 */
@Repository
public class DateFormatMethod implements TemplateMethodModelEx {


    @Override
    public Object exec(List arguments) throws TemplateModelException {
        if (arguments != null && !arguments.isEmpty()) {
            Object obj = arguments.get(0);
            if(obj == null){
                return null;
            }

            String format = "yyyy-MM-dd HH:mm:ss";
            String value = obj.toString();

            obj = arguments.get(1);
            if(obj == null){
                return stampToDate(value, format);
            }

            format =  obj.toString();
            return stampToDate(value, format);
        }

        return null;
    }

    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s, String format){
        try{
            if(StringUtils.isBlank(s)){
                return null;
            }
            String res;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            if(StringUtils.isNotBlank(s) && s.length() == 10){
                s = s + "000";
            }
            long lt = new Long(s);
            Date date = new Date(lt);
            res = simpleDateFormat.format(date);
            return res;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /*
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String s, String format)  {
        try{
            String res;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            Date date = simpleDateFormat.parse(s);
            long ts = date.getTime();
            res = String.valueOf(ts);
            return res;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
